package linkList;

import utils.linkListUtil;
import utils.linkListUtil.ListNode;

public class mergeTwoLists {
    // l1 l2非递减 也就是单调+增
    // 且可能为空
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        } else if (list2 == null) {
            return list1;
        }
        // 均不为null
        // 从小的开始遍历
        // 链表中元素顺序的修改，把他当作变量即可，只不过遍历时，记得取next，要不然就循环出不来了
        ListNode head = null, first = null;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                if (first == null) {
                    first = list1;
                    head = first;
                } else {
                    first.next = list1;
                    first = first.next;
                }
                list1 = list1.next;
            } else {
                if (first == null) {
                    first = list2;
                    head = first;

                } else {
                    first.next = list2;
                    first = first.next;
                }
                list2 = list2.next;
            }

        }
        // 16 234
        // 判断长度
        if (list1 != null) {
            first.next = list1;
        } else if (list2 != null) {
            first.next = list2;
        }
        // else{
        // //相同长度
        // }
        return head;
    }

    public static void main(String[] args) {
        // int[] l1 = new int[] { 1, 2, 4 };
        // int[] l2 = new int[] { 1, 3, 4 };
        int[] l1 = new int[] { 1, 8 };
        int[] l2 = new int[] { 1, 3, 4 };
        ListNode list1 = linkListUtil.createLinkedList(l1);
        ListNode list2 = linkListUtil.createLinkedList(l2);
        ListNode mergeTwoLists = mergeTwoLists(list1, list2);
        while (mergeTwoLists != null) {
            System.out.println(mergeTwoLists.val);
            mergeTwoLists = mergeTwoLists.next;
        }
    }
}
